package cn.wzut.edut.exception;

import cn.wzut.edut.pojo.JsonResult;
import com.auth0.jwt.exceptions.JWTVerificationException;
import jdk.nashorn.internal.parser.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;

/**
 * 统一异常处理类
 * by 叶庭辉
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 业务异常处理
     */
    @ResponseBody
    @ExceptionHandler(ServiceException.class)
    public JsonResult businessExceptionHandler(ServiceException e) {
        log.error(e.getMessage(), e);
        return new JsonResult((int)e.getCode(), e.getMsg());
    }

    /**
     * ConstraintViolationException 异常处理
     */
    @ResponseBody
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult constraintViolationExceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return new JsonResult(-1, e.getMessage());
    }

    /**
     * JWTVerificationException 异常处理
     */
    @ResponseBody
    @ExceptionHandler(JWTVerificationException.class)
    public JsonResult JWTVerificationExceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return new JsonResult(-1, e.getMessage());
    }

    /**
     * Exception 异常处理
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public JsonResult exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return new JsonResult(-1, "未知的服务异常");
    }

}
